package com.guaoran.distributed.io.nio.two.buffer;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * @Author gucheng
 * @Description 编码 / 解码
 * 2019-04-29 16:48
 */
public class BufferByEncodeDemo {
    /**
     * 编码
     * @param str
     */
    public static byte[] encode(String str){
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer.append(str);
        charBuffer.flip();
        // 获取 utf-8 的编码器
        Charset charset = Charset.forName("utf-8");
        ByteBuffer byteBuffer = charset.encode(str);
        // 返回的是 ByteBuffer 内部的数组引用
        byte[] array = byteBuffer.array();
        // 通过 limit 指定有效的返回长度
        byte[] bytes = Arrays.copyOf(byteBuffer.array(), byteBuffer.limit());
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(bytes));
        return bytes;
    }
    /**
     * 解码
     * @param bytes
     */
    public static void decode(byte [] bytes){
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        Charset charset = Charset.forName("utf-8");
        CharBuffer charBuffer = charset.decode(byteBuffer);
        char[] array = charBuffer.array();
        // 通过指定 limit 获得有效长度
        char[] arrays = Arrays.copyOf(charBuffer.array(),charBuffer.limit());
        System.out.println(array);
        System.out.println(arrays);
    }

    public static void main(String[] args) {
        BufferByEncodeDemo.decode(BufferByEncodeDemo.encode("孤傲然"));
    }
}
